/* File parser.mly -- ocamlyacc parser */
%{

open Configfile

let default_section = "DEFAULT"

(* Right strip string of spaces *)
let rstrip s chars =
  let goodchar c = not (String.contains chars c) in
  let rec loop = function
    | -1 -> -1
    | n -> if goodchar s.[n] then n else loop (n-1)
  in
  let endpos = loop ((String.length s)-1) in
  if endpos < 0 then
    ""
  else
    String.sub s 0 (endpos+1)


(* Un-quote the given string *)
let unquote (opt, s) =
  let l = String.length s in
  if l > 0 && s.[0] = '"' then
    let e = String.rindex s '"' in
    if e = 0 || e = 1 then
      opt,""
    else
      opt,String.sub s 1 (e-1)
  else
    opt,(rstrip s " \t")

(* Useful for producing error messages *)
(* BUGFIX: Do *NOT* raise Parsing.parse_error in here *)

let raise_error pos descr =
    Printf.eprintf "Parser error: %s: %s\n"
        (Configutil.string_of_pos pos) descr;
    failwith "Syntax error in file";
;;

let start_pos () = Parsing.symbol_start_pos ()
let end_pos () = Parsing.symbol_end_pos ()
let rhs_pos t = Parsing.rhs_start_pos t

;;


%}

%token <string> SECTION
%token <string * string> OPTION
%token EOF

%start main
%type <(string * (string * string) list) list> main

%%

main:
  | EOF				{ [] }
  | sections EOF		{ $1 }
  | options sections EOF	{ (default_section, $1) :: $2}
;


sections:
  | SECTION options 		{ [$1, $2] }
  | SECTION options sections	{ ($1, $2) :: $3 }
;

options:
  | OPTION 			{ [unquote $1] }
  | OPTION options		{ (unquote $1) :: $2 }
;




